const spawn = require('child_process').spawn;
const exec  = require('child_process').exec;
const _     = require('lodash');
const os    = require('os');
const iconv = require('iconv-lite');

let N1, D1;
// getProcessCPUUSage();

getProcessTask();

function getProcessTask () {
    let cmds = ' tasklist /V /FO CSV /NH /FI "PID EQ 6304"';
    let ps   = exec(cmds, (err, out) => {
        // iconv.skipDecodeWarning = true;
        // return;
        let name  = _.trim(_.trimEnd(out, os.EOL), '"').split('","')[8];
        let name2 = Buffer.from(name);
        console.log(iconv.encode(name, 'gb2312').toString());
    });
    
    ps.on('error', err => {
        console.log('error', err);
    });
    
    ps.on('exit', code => {
        process.exit(code);
    });
}

function getProcessCPUUSage () {
    
    /*鼠标移入暂停刷新*/
    /*历史进程*/
    /*选择列*/
    /*搜索pid*/
    /*搜索进程名*/
    /*搜索描述*/
    /*搜索命令行*/
    /*搜索文件路径*/
    /*支持暂停*/
    /*设置刷新时间*/
    /*清理图标缓存*/
    
    /*获取核心数->获取所有任务->获取状态、用户名->计算cpu使用率->获取图标（带缓存）*/
    
    /*获取cpu核心数*/
    /*wmic cpu get NumberOfCores /value*/
    
    /*查询所有任务*/
    /*wmic process where ProcessId=17588 get Name,Description,CommandLine,ProcessId,ParentProcessId,WorkingSetSize,ExecutablePath,SessionId /value*/
    
    /*获取状态、用户名*/
    /*tasklist /V /FO CSV /NH /FI "PID EQ 17588"*/
    /* "msedge.exe","12300","Console","1","348,828 K","Running","EXI-LENOVO\e-xi","0:02:01","暂缺" */
    
    /*计算cpu使用率*/
    let cmd    = '/s /c ' +
        'wmic path Win32_PerfRawData_PerfProc_Process ' +
        'where IDProcess=17588 ' +
        'get Name,IDProcess,PercentProcessorTime,Timestamp_Sys100NS ' +
        '/value';
    let ps     = spawn('cmd.exe', cmd.split(' '));
    let output = '';
    
    /*捕获标准输出并将其打印到控制台*/
    ps.stdout.on('data', data => output += data);
    
    /*捕获标准错误输出并将其打印到控制台*/
    ps.stderr.on('data', data => console.log(data.toString()));
    
    /*注册子进程关闭事件*/
    ps.on('exit', (code) => {
        if (code) {
            console.log(`[Abnormal exit]`, code);
            return;
        }
        
        let N2 = /PercentProcessorTime=(\d+)/g.exec(output);
        let D2 = /Timestamp_Sys100NS=(\d+)/g.exec(output);
        N2     = (N2 && N2[1]) ? N2[1] : '0';
        D2     = (D2 && D2[1]) ? D2[1] : '0';
        N1     = N1 ? N1 : N2;
        D1     = D1 ? D1 : D2;
        
        if (N1 && D1) {
            // let CPUUSage = (arrayDiff(N2, N1) / arrayDiff(D2, D1)) * 100;
            let CPUUSage = ((N2 - N1) / (D2 - D1) / 8) * 100;
            CPUUSage     = CPUUSage ? CPUUSage : 0;
            console.log(CPUUSage.toFixed(1));
            N1 = N2;
            D1 = D2;
        }
        setTimeout(getProcessCPUUSage, 1000);
    });
}
